//
//  UserAccountManager.swift
//  swift_learning
//
//  Created by aron on 2017/2/1.
//  Copyright © 2017年 arons. All rights reserved.
//

import Foundation

class UserAccountManager {
    
    static let sharedInstance : UserAccountManager = {
        return UserAccountManager()
    }()
    
    /// 账号信息存储路径
    var accountPath : String {
        let docPaht : String = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first!
        return (docPaht as NSString).appendingPathComponent("account.plist")
    }
    
    /// 账号信息
    var account : UserAccount?
    
    init() {
        print("accountPath = \(accountPath)")
        restoreAccount()
    }
    
    /// 读取账号信息
    private func restoreAccount() {
        account = NSKeyedUnarchiver.unarchiveObject(withFile: accountPath) as! UserAccount?
    }
    
    // MARK: - ......::::::: public :::::::......
    
    /// 保存账号信息
    ///
    /// - Parameter account: 账号
    func saveAccount(account : UserAccount) {
        self.account = account
        NSKeyedArchiver.archiveRootObject(account, toFile: accountPath)
    }
    
    func isLogin() -> Bool {
        if account == nil {
            return false
        }
        
        guard let accessToken = account?.access_token else{
            return false
        }
        
        guard let expireDate = account?.expiresDate else {
            return false
        }
        
        return expireDate.compare(Date()) == .orderedDescending
    }
    
}
